package com.aizuda.boot.modules.business.contract.controller;



import com.aizuda.boot.modules.business.contract.entity.EmployeeTableHeaderEntity;
import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.contract.entity.dto.UpdateHeaderRequestDTO;
import com.aizuda.boot.modules.business.contract.entity.vo.ContractDTO;
import com.aizuda.boot.modules.business.contract.entity.vo.FieldDTO;
import com.aizuda.boot.modules.business.contract.mapper.ContractFieldMapper;
import com.aizuda.boot.modules.business.contract.service.EmployeeTableHeaderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/contract/header")
@Tag(name = "员工表头配置")
@RequiredArgsConstructor
public class EmployeeTableHeaderController {
    @Resource
    private EmployeeTableHeaderService headerService;
    @Resource
    private ContractFieldMapper contractFieldMapper;


    @PostMapping("/update")
    @Operation(summary = "更新员工表头配置")
    public SingleResponse updateHeader(@RequestBody UpdateHeaderRequestDTO request) {
        headerService.updateHeadersByEmployeeId(request.getEmployeeId(), request.getHeaders());
        return SingleResponse.success();
    }

    @GetMapping("/{employeeId}")
    @Operation(summary = "根据员工ID查询表头配置")
    public SingleResponse<EmployeeTableHeaderEntity> getHeadersByEmployeeId(@PathVariable Long employeeId) throws Exception {
        EmployeeTableHeaderEntity config = headerService.getByEmployeeId(employeeId);
        
        // 如果没有配置或者headers为空，创建默认配置
        if (config == null || config.getHeaders() == null || config.getHeaders().trim().isEmpty()) {
            // 创建新的配置记录，让数据库默认值生效
            EmployeeTableHeaderEntity newConfig = new EmployeeTableHeaderEntity();
            newConfig.setEmployeeId(employeeId);
            // 不设置headers字段，让数据库默认值生效
            headerService.save(newConfig);
            
            // 重新查询获取带有默认值的配置
            config = headerService.getByEmployeeId(employeeId);
            
            // 如果重新查询后仍然没有headers，返回空配置
            if (config == null || config.getHeaders() == null || config.getHeaders().trim().isEmpty()) {
                config = new EmployeeTableHeaderEntity();
                config.setEmployeeId(employeeId);
                config.setHeaders("[]"); // 设置空数组作为默认值
                config.setFields(new ArrayList<>());
                return SingleResponse.of(config);
            }
        }
        
        String headersStr = config.getHeaders(); // 假设是 "[5,23,2,6,7,8,9]"
        // 去除中括号
        headersStr = headersStr.replace("[", "").replace("]", "");
        
        // 如果是空字符串，返回空字段列表
        if (headersStr.trim().isEmpty()) {
            config.setFields(new ArrayList<>());
            return SingleResponse.of(config);
        }
        
        // 按逗号分割
        String[] parts = headersStr.split(",");
        // 转换为整数列表
        List<Integer> headers = Arrays.stream(parts)
                .map(String::trim)
                .filter(s -> !s.isEmpty()) // 过滤空字符串
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        
        List<ContractDTO.ModuleDTO.FieldDTO> fieldByIds = contractFieldMapper.findFieldByIds(headers);
        config.setFields(fieldByIds);
        return SingleResponse.of(config);
    }

    /**
     * 获取所有员工表头配置
     * @param fieldName 字段名称（可选，支持模糊匹配）
     * @return
     */
    @GetMapping("/all")
    @Operation(summary = "获取所有员工表头配置")
    public SingleResponse<List<FieldDTO>> getAllHeaders(@RequestParam(value = "fieldName", required = false) String fieldName) {
        List<FieldDTO> allFields;
        if (fieldName != null && !fieldName.trim().isEmpty()) {
            // 如果传入了字段名称，进行模糊匹配查询
            allFields = contractFieldMapper.findHeadersByFieldName(fieldName.trim());
        } else {
            // 如果没有传入字段名称，查询所有字段
            allFields = contractFieldMapper.findAllHeaders();
        }
        return SingleResponse.of(allFields);
    }
}
